package com.warm.base.design.c_singleton;

import java.io.Serializable;

/**
 * @Date: 2020/3/17 10:48
 * @Author: LChuang
 * @Description: 考虑到 Java 创建对象的几种方式, 引申到几种破坏单例模式的情况
 *
 *   推荐使用 枚举方式 创建单例模式
 */
public class SafeSingleton implements Serializable, Cloneable {


    // 在类初始化期间，执行由JVM保证线程安全
    private static SafeSingleton singleton = new SafeSingleton();

    public static SafeSingleton getInstance(){
        return singleton;
    }

    /** 避免反射和多类加载器破坏 */
    private SafeSingleton(){
        if(SafeSingleton.singleton != null){
            throw new InstantiationError("not allow");
        }
    }

    /** 避免克隆破坏*/
    @Override
    protected Object clone() throws CloneNotSupportedException{
        throw new CloneNotSupportedException("not allow");
    }

    /** 避免反序列化破坏*/
    protected Object readResolve(){
        return singleton;
    }
}
